﻿Public Partial Class Wfrm_Mantenedor
    Inherits Wfrm_Master
    Public Delegate Sub CustomLoadEvent(ByVal sender As Object, ByVal e As EventArgs)
    Public Event DropDownList As CustomLoadEvent


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            ViewState("formulario") = Request("ID")
            ViewState("usuario") = "jquintanilla"
            Carga_Sp_Busqueda()
        End If
        Carga_Inicial()
    End Sub
    Sub GeneraColumnas()
        'Dim col As System.Web.UI.WebControls.DataGridColumn
        'col.HeaderText = "test1"
        'col.


        'Grid_Resultado.Columns.Add(col)
        'Grid_Resultado.Columns(0)

    End Sub
    Sub Carga_Sp_Busqueda()
        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        EXEC.ExecuteDataTable(Rp, "select * from SYS_FORM where id_form =" & ViewState("formulario"))

        If Rp.TieneDatos Then
            lbl_titulo.Text = Rp.DtTable.Rows(0).Item("titulo_form")
            ViewState("sp_busqueda") = Rp.DtTable.Rows(0).Item("sp_busqueda")
            ViewState("tabla") = Rp.DtTable.Rows(0).Item("tabla")
            ViewState("sp_save") = Rp.DtTable.Rows(0).Item("sp_save")
            ViewState("sp_carga_objetos") = Rp.DtTable.Rows(0).Item("sp_carga_objetos")
            ViewState("sp_delete") = Rp.DtTable.Rows(0).Item("sp_delete")            
        End If

    End Sub

    Sub Carga_Inicial()
        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        Rp.StoredProcedure = "SP_GET_FORM_INICIAL"
        Rp.AddParametro(ViewState("formulario"))
        EXEC.ExecuteDataTable(Rp)
     

        If Rp.TieneDatos Then
            Dim i As Integer

            For i = 0 To Rp.DtTable.Rows.Count - 1
                Dim Fila As New TableRow
                Dim celda1 As New TableCell
                Dim celda2 As New TableCell
                Dim lbl As New Label
                Dim txt As Anthem.TextBox
                Dim cmb As Anthem.DropDownList
                Dim chk As Anthem.CheckBox

                Dim tipo_objeto As String = Rp.DtTable.Rows(i).Item("tipo_objeto")
                lbl.Text = Rp.DtTable.Rows(i).Item("texto_label")
                If Rp.DtTable.Rows(i).Item("visible") = 0 Then
                    lbl.Visible = False
                End If

                If tipo_objeto = "TEXTBOX" Then
                    txt = New Anthem.TextBox
                    txt.ID = Rp.DtTable.Rows(i).Item("id_objeto")
                    txt.Width = Val(Rp.DtTable.Rows(i).Item("ancho").ToString())
                    txt.UpdateAfterCallBack = True
                    If Rp.DtTable.Rows(i).Item("DEFAULT_VALUE").ToString().Length > 0 Then
                        txt.Text = Rp.DtTable.Rows(i).Item("DEFAULT_VALUE")                    
                    End If
                    If Not Rp.DtTable.Rows(i).Item("onchange_object").ToString() = "" Then
                        AddHandler txt.TextChanged, AddressOf txt_Changed
                        txt.EnableCallBack = True
                        txt.AutoCallBack = True
                        txt.EnabledDuringCallBack = False
                        txt.TextDuringCallBack = "Cargando..."

                        ViewState(txt.ID & "_onchange_object") = Rp.DtTable.Rows(i).Item("onchange_object")
                        ViewState(txt.ID & "_onchange_sp") = Rp.DtTable.Rows(i).Item("onchange_sp")
                        ViewState(txt.ID & "_onchange_value") = Rp.DtTable.Rows(i).Item("onchange_value")
                        ViewState(txt.ID & "_onchange_text") = Rp.DtTable.Rows(i).Item("onchange_text")

                    End If

                    If Rp.DtTable.Rows(i).Item("visible") = 0 Then
                        txt.Visible = False
                    End If
                    If Rp.DtTable.Rows(i).Item("readonly") = 1 Then
                        txt.ReadOnly = True
                    End If
                    If Rp.DtTable.Rows(i).Item("calendar").ToString() = "S" Then
                        txt.CssClass = "campofecha" 'Attributes.Add("onclick", "cal(this.id)")                        
                    End If

                    celda2.Controls.Add(txt)
                End If
                If tipo_objeto = "CHECKBOX" Then
                    chk = New Anthem.CheckBox
                    chk.Width = Val(Rp.DtTable.Rows(i).Item("ancho").ToString())
                    chk.UpdateAfterCallBack = True
                    If Rp.DtTable.Rows(i).Item("visible") = 0 Then
                        chk.Visible = False
                    End If
                    If Rp.DtTable.Rows(i).Item("readonly") = 1 Then
                        chk.Enabled = False
                    End If
                    celda2.Controls.Add(chk)
                End If

                If tipo_objeto = "DROPDOWNLIST" Then
                    cmb = New Anthem.DropDownList
                    cmb.Width = Val(Rp.DtTable.Rows(i).Item("ancho").ToString())
                    cmb.ID = Rp.DtTable.Rows(i).Item("id_objeto")
                    cmb.AutoCallBack = False
                    cmb.EnableCallBack = False

                    If Rp.DtTable.Rows(i).Item("visible") = 0 Then
                        cmb.Visible = False
                    End If
                    If Rp.DtTable.Rows(i).Item("readonly") = 1 Then
                        cmb.Enabled = False
                    End If

                    If Not Rp.DtTable.Rows(i).Item("sp_carga").ToString() = "" Then
                        Dim Rp2 As New DotNetResponse.SQLPersistence
                        Rp2.StoredProcedure = Rp.DtTable.Rows(i).Item("sp_carga").ToString()
                        EXEC.ExecuteDataTable(Rp2)
                        cmb.DataSource = Rp2.DtTable
                        cmb.DataValueField = Rp.DtTable.Rows(i).Item("drop_value")
                        cmb.DataTextField = Rp.DtTable.Rows(i).Item("drop_text")


                        If Not Rp.DtTable.Rows(i).Item("onchange_object").ToString() = "" Then
                            AddHandler cmb.SelectedIndexChanged, AddressOf DropDownList_SelectedIndexChanged
                            cmb.EnableCallBack = True
                            cmb.EnabledDuringCallBack = False
                            cmb.TextDuringCallBack = "Cargando..."
                            cmb.AutoCallBack = True
                            cmb.AutoPostBack = True

                            ViewState(cmb.ID & "_onchange_object") = Rp.DtTable.Rows(i).Item("onchange_object")
                            ViewState(cmb.ID & "_onchange_sp") = Rp.DtTable.Rows(i).Item("onchange_sp")
                            ViewState(cmb.ID & "_onchange_value") = Rp.DtTable.Rows(i).Item("onchange_value")
                            ViewState(cmb.ID & "_onchange_text") = Rp.DtTable.Rows(i).Item("onchange_text")

                        End If

                        cmb.DataBind()
                    End If

                    If Rp.DtTable.Rows(i).Item("DEFAULT_VALUE").ToString().Length > 0 Then
                        If Rp.DtTable.Rows(i).Item("DEFAULT_VALUE") <> -99 Then
                            cmb.SelectedValue = Rp.DtTable.Rows(i).Item("DEFAULT_VALUE")
                        End If
                    Else
                        cmb.SelectedValue = 0
                    End If

                    cmb.UpdateAfterCallBack = True
                    celda2.Controls.Add(cmb)
                End If

                celda1.Controls.Add(lbl)

                Fila.Cells.Add(celda1)
                Fila.Cells.Add(celda2)


                Table1.Rows.Add(Fila)

            Next
        End If
    End Sub

    Sub Crear_Ingreso_Datos()
        
    End Sub
 
    Protected Sub Btn_Buscar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Btn_Buscar.Click
        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        Rp.StoredProcedure = ViewState("sp_busqueda")
        Rp.AddParametro(ME.txt_busqueda.Text.TRIM )
        EXEC.ExecuteDataTable(Rp)
        Grid_Resultado.DataSource = Rp.DtTable
        Grid_Resultado.DataBind()
        Grid_Resultado.UpdateAfterCallBack = True

        If Not Rp.TieneDatos Then
            MsgInformativo("No se ha encontrado información")
        End If
        If Rp.Errores Then
            MsgError(Rp.MensajeError)
        End If

    End Sub
    Protected Sub txt_Changed(ByVal sender As Object, ByVal e As EventArgs)


        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence

        Rp.StoredProcedure = ViewState(sender.ID & "_onchange_sp")
        Rp.AddParametro(Grid_Resultado.SelectedItem.Cells(1).Text)
        EXEC.ExecuteDataTable(Rp)

        If Rp.TieneDatos Then
            Dim i As Integer
            For i = 0 To Rp.DtTable.Rows.Count - 1
                Dim j As Integer
                For j = 0 To Rp.DtTable.Columns.Count - 1
                    AsignarValueControl(Rp.DtTable.Columns(j).ColumnName, Rp.DtTable.Rows(i).Item(j).ToString())
                Next
            Next
        End If
        If Rp.Errores Then
            MsgError(Rp.MensajeError)
        End If

    End Sub

    Protected Sub DropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Try


            Dim objeto As String = ViewState(sender.ID & "_onchange_object")
            Dim sp As String = ViewState(sender.ID & "_onchange_sp")
            Dim DataTextField As String = ViewState(sender.ID & "_onchange_text")
            Dim DataValueField As String = ViewState(sender.ID & "_onchange_value")


            Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
            Dim Rp2 As New DotNetResponse.SQLPersistence
            Rp2.StoredProcedure = sp
            Rp2.AddParametro(DirectCast(sender, Anthem.DropDownList).SelectedValue)
            EXEC.ExecuteDataTable(Rp2)
            Dim cmb As Anthem.DropDownList
            cmb = Table1.FindControl(objeto)
            cmb.SelectedValue = 0

            cmb.DataSource = Rp2.DtTable
            cmb.DataValueField = DataValueField
            cmb.DataTextField = DataTextField
            cmb.EnableCallBack = True
            cmb.EnabledDuringCallBack = False
            cmb.TextDuringCallBack = "Cargando..."
            cmb.AutoCallBack = True
            cmb.DataBind()
            cmb.UpdateAfterCallBack = True
        Catch ex As Exception

        End Try

    End Sub

    Protected Sub Grid_Resultado_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Grid_Resultado.SelectedIndexChanged


        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence

        Rp.StoredProcedure = ViewState("sp_carga_objetos")
        Rp.AddParametro(Grid_Resultado.SelectedItem.Cells(1).Text)
        EXEC.ExecuteDataTable(Rp)

        If Rp.TieneDatos Then
            Dim i As Integer
            For i = 0 To Rp.DtTable.Rows.Count - 1
                Dim j As Integer
                For j = 0 To Rp.DtTable.Columns.Count - 1
                    AsignarValueControl(Rp.DtTable.Columns(j).ColumnName, Rp.DtTable.Rows(i).Item(j).ToString())
                Next
            Next
        End If
        If Rp.Errores Then
            MsgError(Rp.MensajeError)
        End If
    End Sub

    Protected Sub Btn_Grabar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Btn_Grabar.Click

        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        Dim Rpi As New DotNetResponse.SQLPersistence
        Rpi.StoredProcedure = ViewState("sp_save")

        Rp.StoredProcedure = "SP_GET_FORM_INICIAL"
        Rp.AddParametro(ViewState("formulario"))
        EXEC.ExecuteDataTable(Rp)

        Dim csql As String = ""
        Dim Insert As Boolean = True

        If Rp.TieneDatos Then
            Dim i As Integer
            For i = 0 To Rp.DtTable.Rows.Count - 1
                Dim Valor As String = GetValueControl(Rp.DtTable.Rows(i).Item("Id_objeto"))

                'If Rp.DtTable.Rows(i).Item("ind_pk").ToString.Trim = "S" And Valor.Length > 0 Then
                '    Insert = False
                'End If

                If Rp.DtTable.Rows(i).Item("OBLIGATORIO_S_N").ToString().ToUpper = "S" And Valor.Length = 0 Then
                    MsgError("Falta ingresar " & Rp.DtTable.Rows(i).Item("TEXTO_LABEL").ToString())
                    Exit Sub
                End If
                If Rp.DtTable.Rows(i).Item("Tipo_Validacion1").ToString() = "RUT" Then
                    If Not DotNetDal.Generica.ValidaRut(Valor) Then
                        MsgError("Rut inválido")
                        Exit Sub
                    End If

                End If
                If Rp.DtTable.Rows(i).Item("Tipo_Validacion1").ToString() = "FECHA" Then
                    Valor = DotNetDal.Generica.FormatFecha(Valor)
                    If Not IsDate(Valor) Then
                        MsgError("Fecha inválida")
                        Exit Sub
                    End If
                End If

                Rpi.AddParametroName(Rp.DtTable.Rows(i).Item("Id_objeto"))
                Rpi.AddParametro(Valor)
            Next
            Rpi.AddParametro(ViewState("usuario"))

            Dim EXECin As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
            EXECin.ExecuteDataTable(Rpi)
            EXECin.Commit()

            If Rpi.Errores Then
                MsgError(Rpi.MensajeError)
            Else
                MsgInformativo("Grabado con éxito")
                Btn_Buscar_Click(Nothing, Nothing)
            End If

        End If

    End Sub
    Sub AsignarValueControl(ByVal Ctl As String, ByVal Valor As String)
        Try
            Dim ct = Table1.FindControl(Ctl)
            If ct.ToString = "Anthem.TextBox" Then
                DirectCast(ct, Anthem.TextBox).Text = Valor
                DirectCast(ct, Anthem.TextBox).UpdateAfterCallBack = True
            End If
            'Anthem.DropDownList
            If ct.ToString = "Anthem.DropDownList" Then
                Try
                    DirectCast(ct, Anthem.DropDownList).SelectedValue = Valor
                    DirectCast(ct, Anthem.DropDownList).UpdateAfterCallBack = True

                    DropDownList_SelectedIndexChanged(DirectCast(ct, Anthem.DropDownList), Nothing)
                Catch ex As Exception

                End Try
            End If
        Catch ex As Exception
        End Try
    End Sub
    Function GetValueControl(ByVal Ctl As String) As String
        Dim ct = Table1.FindControl(Ctl)
        If ct.ToString = "Anthem.TextBox" Then
            Return DirectCast(ct, Anthem.TextBox).Text.Trim()
        End If
        'Anthem.DropDownList
        If ct.ToString = "Anthem.DropDownList" Then
            Try
                Return DirectCast(ct, Anthem.DropDownList).SelectedValue
            Catch ex As Exception
                Return Nothing
            End Try

        End If

    End Function

    Sub ClearControl(ByVal Ctl As String)
        Dim ct = Table1.FindControl(Ctl)
        If ct.ToString = "Anthem.TextBox" Then
            DirectCast(ct, Anthem.TextBox).Text = ""
        End If
        'Anthem.DropDownList
        If ct.ToString = "Anthem.DropDownList" Then
            Try
                DirectCast(ct, Anthem.DropDownList).SelectedValue = 0
            Catch ex As Exception

            End Try

        End If

    End Sub

    Protected Sub Btn_Limpiar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Btn_Limpiar.Click
        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        Dim Rpi As New DotNetResponse.SQLPersistence
        Rpi.StoredProcedure = ViewState("sp_save")

        Rp.StoredProcedure = "SP_GET_FORM_INICIAL"
        Rp.AddParametro(ViewState("formulario"))
        EXEC.ExecuteDataTable(Rp)

        If Rp.TieneDatos Then
            Dim i As Integer
            For i = 0 To Rp.DtTable.Rows.Count - 1
                ClearControl(Rp.DtTable.Rows(i).Item("Id_objeto"))
            Next
        End If
    End Sub

    <Anthem.Method()> _
   Public Function Eliminar(ByVal Id_Prueba As String)
        If Session("ID") Is Nothing Then
            Return Nothing
        End If
        Dim EXEC As New DotNetDal.SQLPersistence(False, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Dim Rp As New DotNetResponse.SQLPersistence
        Dim Rpi As New DotNetResponse.SQLPersistence

        Rp.StoredProcedure = "SP_GET_FORM_INICIAL"
        Rp.AddParametro(ViewState("formulario"))
        EXEC.ExecuteDataTable(Rp)

        If Rp.TieneDatos Then
            Dim i As Integer
            For i = 0 To Rp.DtTable.Rows.Count - 1
                Dim Valor As String = GetValueControl(Rp.DtTable.Rows(i).Item("Id_objeto"))
                If Rp.DtTable.Rows(i).Item("ind_pk").ToString.ToUpper = "S" Then
                    If Valor.Trim = "" Then
                        MsgInformativo("Imposible Eliminar")
                        Session.Remove("ID")
                        Exit Function
                    End If
                    Rpi.AddParametro(Valor)
                End If
            Next
            Rpi.AddParametro(ViewState("usuario"))
        End If

        Dim EXECin As New DotNetDal.SQLPersistence(True, "cnn", DotNetDal.SQLPersistence.Provider.SQLCLIENT)
        Rpi.StoredProcedure = ViewState("sp_delete")
        EXECin.ExecuteNonQuery(Rpi)
        EXECin.Commit()
        If Rpi.Errores Then
            MsgError(Rpi.MensajeError)
        Else
            MsgInformativo("Eliminado con éxito")
            Btn_Buscar_Click(Nothing, Nothing)
        End If

        Session.Remove("ID")
    End Function

    Protected Sub Btn_Eliminar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Btn_Eliminar.Click
        MsgConfirm("¿Confirma Eliminar?", "function(r){ if(r){Anthem_InvokePageMethod('Eliminar',[" & Session("ID") & "],function(result) {});} }")
        Session("ID") = 1
    End Sub
End Class